package ip.ejb.sequence;

import javax.ejb.*;
import javax.naming.*;
//import java.rmi.RemoteException;
import java.util.Hashtable;

/**
 * @ejb.bean
 *   name="SequenceSession" 
 *   type="Stateless"
 *   jndi-name="ejb/util/SequenceSession"
 *   local-jndi-name="ejb/util/SequenceSessionLocal"
 * @ejb.transaction type="Required"
 */

public class SequenceSessionBean implements SessionBean {

  public static final int BLOCK_SIZE = 10;
  protected SessionContext ctx;
  static protected Hashtable sequences;

  /**
   * @ejb.interface-method
   */

  public int getNextValue(String sequenceName) {
    Block block = (Block)sequences.get(sequenceName);
    if (block == null || block.isEmpty()) {
      // allocate
      SequenceLocalHome home = null;
      SequenceLocal entity = null;
      try {
        home = (SequenceLocalHome)(new InitialContext()).lookup("ejb/util/SequenceLocal");
      } catch (Exception ex) {
        System.out.println("SHIT: Cannot lookup for sequence entity home!");
      }
      try {
        entity = home.findByPrimaryKey(new SequencePK(sequenceName));
      } catch (FinderException ex) {
        try {
          entity = home.create(sequenceName, 1);
        } catch (CreateException ex2) {
          System.out.println("SHIT: Cannot create sequence entity bean!");
        }
      }
      int start = entity.getBlock(BLOCK_SIZE);
      block = new Block(start, start + BLOCK_SIZE - 1);
      sequences.put(sequenceName, block);
    }
    return block.getNumber();
  }

  /**
   * @ejb.create-method
   */
  public void ejbCreate() throws javax.ejb.CreateException {
    if(sequences == null)
        sequences = new Hashtable();
  }

  public void ejbRemove() {
  }

  public void ejbActivate() {
  }

  public void ejbPassivate() {
  }

  public void setSessionContext(SessionContext ctx) {
    this.ctx = ctx;
  }

}